﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QDebug>
#include "DataWriter.h"
#include <QMessageBox>

#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    setWindowTitle(QApplication::applicationDisplayName());

    connect(ui->toolButton_rule, &QToolButton::clicked, this, &MainWindow::rulePathSet);
    connect(ui->toolButton_excel, &QToolButton::clicked, this, &MainWindow::excelPathSet);
    connect(ui->toolButton_log, &QToolButton::clicked, this, &MainWindow::logPathSet);
    connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::start);

    // connect(ui->comboBox_Sheet, &QComboBox::currentTextChanged, this, [&](){
    //     QXlsx::Document doc(ui->lineEdit_excel->text());
    //     if (!doc.load()) return;
    //     doc.selectSheet(ui->comboBox_Sheet->currentText());
    //     m_RowCount = doc.dimension().rowCount();

    // });

    ui->progressBar->setValue(0.0);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::rulePathSet()
{
    m_RR = new RuleReader("Json Files (*.json)");
    if (m_RR && !m_RR->getFilePath().isEmpty()) {
        ui->lineEdit_rule->setText(m_RR->getFilePath());
        m_RR->readFile();
        ui->comboBox_case->clear();
        ui->comboBox_case->addItems(m_RR->getCaseList());
    }
}

void MainWindow::excelPathSet()
{
    // m_DR = new DataSheetReader("Excel Files (*.xls *.xlsx)");
    // if (m_DR && !m_DR->getFilePath().isEmpty()) {
    //     ui->lineEdit_excel->setText(m_DR->getFilePath());
    //     m_DR->readFile();
    //     ui->comboBox_Sheet->clear();;
    //     ui->comboBox_Sheet->addItems(m_DR->getSheetsName());
    // }
    QString filePath = QFileDialog::getOpenFileName(this, u8"设置数据表格文件路径", QApplication::applicationDirPath(), "Excel Files (*.xls *.xlsx)");
    if (!filePath.isEmpty()) ui->lineEdit_excel->setText(filePath);

    QXlsx::Document doc(ui->lineEdit_excel->text());
    if (!doc.load()) return;

    // m_RowCount = doc.dimension().rowCount();
    ui->comboBox_Sheet->clear();
    ui->comboBox_Sheet->addItems(doc.sheetNames());
}

void MainWindow::logPathSet()
{
    // m_LR = new LogReader("Log Files (*.txt *.log)");
    // if (m_LR && !m_LR->getFilePath().isEmpty()) ui->lineEdit_log->setText(m_LR->getFilePath());
    QString dir = QFileDialog::getExistingDirectory(this, u8"设置日志目录", QApplication::applicationDirPath());
    if (!dir.isEmpty()) ui->lineEdit_log->setText(dir);
}

void MainWindow::start()
{
    if (!m_RR) return;

    m_threadNum = 0;
    m_maxThreadNum = 0;

    ui->pushButton->setDisabled(true);
    ui->progressBar->setValue(0);
    // QXlsx::Document doc(ui->lineEdit_excel->text());
    // if (!doc.load()) return;

    // int rowCount = doc.dimension().rowCount();

    // ui->comboBox_Sheet->addItems(doc.sheetNames());

    uint start = ui->spinBox_start->text().toUInt();
    uint end = ui->spinBox_end->text().toUInt();

    uint totalCount = end - start;

    QDir directory(ui->lineEdit_log->text());

    if (!directory.exists()) {
        qDebug() << "Log Directory does not exist.";
        return;
    }

    QFileInfoList fileList = directory.entryInfoList();

    int fileCount = 0;
    for (auto const &fileInfo : std::as_const(fileList)) {
        if(fileInfo.isDir()) continue;
        ++fileCount;
    }



    uint countPerThread = 1;
    if (totalCount % THREAD_NUMBER != 0) countPerThread = totalCount / THREAD_NUMBER + 1;
    else countPerThread = totalCount / THREAD_NUMBER;

    if (doc) {
        doc->save();
        delete doc;
    }

    doc = new QXlsx::Document(ui->lineEdit_excel->text());
    doc->selectSheet(ui->comboBox_Sheet->currentText());
    doc->save();


    for(int n = 0; n < THREAD_NUMBER; ++n) {
        if (start > m_RowCount) break;

        uint count = countPerThread;
        if (totalCount - countPerThread * n < countPerThread) {
            count = totalCount - countPerThread * n;
        }


        DataWriter* pDR = new DataWriter(doc->sheet(ui->comboBox_Sheet->currentText()));

        // pDR->setActivateSheet(ui->comboBox_Sheet->currentText());
        pDR->setParam(ui->lineEdit_log->text(),
                       m_RR->getColumnObjects(ui->comboBox_case->currentText()),
                       m_RR->getLogFileters(ui->comboBox_case->currentText()),
                       ui->lineEdit_CycleEndFlag->text(),
                       start,
                       count);
        QThread* thread = new QThread;
        pDR->moveToThread(thread);
        connect(thread, &QThread::started, pDR, &DataWriter::run1);
        connect(pDR, &DataWriter::threadFinished, thread, &QThread::quit);
        connect(pDR, &DataWriter::threadFinished, pDR, &DataWriter::deleteLater);
        connect(thread, &QThread::finished, thread,&QThread::deleteLater);
        connect(pDR, &DataWriter::processedOneFile, ui->progressBar, [&]{
            ui->progressBar->setValue(ui->progressBar->value() + 1);
        });
        connect(thread, &QThread::finished, this, [&](){
            if (++m_threadNum == m_maxThreadNum) {
                ui->pushButton->setEnabled(true);
                doc->save();
                QMessageBox::information(this, u8"提示", u8"处理已完成！");
            }
        });
        start += count;
        thread->start();
        ++m_maxThreadNum;
    }

    ui->progressBar->setMaximum(m_maxThreadNum * fileCount);


}
